package com.j1ay.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j1ay.forum.dao.mapper.PermissionMapper;
import com.j1ay.forum.model.pojo.po.Permission;
import com.j1ay.forum.model.dto.params.PageParams;
import com.j1ay.forum.service.PermissionService;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.model.pojo.vo.PageResult;
import com.j1ay.forum.model.pojo.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author J1ay
 * @Date 2021/12/18 20:42
 * @Description 权限
 */

@Service
public class PermissionServiceImpl implements PermissionService {


    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    /**
     * 查看权限列表
     * @param pageParams
     * @return
     */
    @Override
    public Result getPermissionList(PageParams pageParams) {
        Page<Permission> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageParams.getQueryString())) {
            queryWrapper.eq(Permission::getName, pageParams.getQueryString());
        }

        Page<Permission> permissionPage = this.permissionMapper.selectPage(page, queryWrapper);
        PageResult<Permission> pageResult = new PageResult<>();
        pageResult.setList(permissionPage.getRecords());
        pageResult.setCurrentPage(permissionPage.getCurrent());
        pageResult.setPageSize(permissionPage.getSize());
        pageResult.setTotals(permissionPage.getTotal());

        return Result.success(pageResult);
    }


    @Override
    public Result add(Permission permission) {
        if (StringUtils.isBlank(permission.getName()) || StringUtils.isBlank(permission.getPath())) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        this.permissionMapper.insert(permission);
        return Result.success(null);
    }

    @Override
    public Result update(Permission permission) {
        if (null == permission.getId()) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        this.permissionMapper.updateById(permission);
        return Result.success(null);
    }

    @Override
    public Result delete(Long id) {
        if (null == id) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        this.permissionMapper.deleteById(id);
        return Result.success(null);
    }

}
